<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生产过程管理系统 - 部门经理</title>
    <link rel="stylesheet" href="../../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../../css/style.css">

    <!-- 引入 jQuery-->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- 引入 Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <style>
        .submenu {
            display: none;
        }

        .menu-item.active > .submenu {
            display: block;
        }

        .menu-arrow {
            transition: transform 0.2s;
        }

        .menu-item.active > a > .menu-arrow {
            transform: rotate(90deg);
        }

        .table th {
            background-color: #f8f9fa;
        }

        /* 添加选中项的样式 */
        .submenu li a.active {
            color: #28a745;
            font-weight: bold;
            transform: translateY(2px);
            display: inline-block;
        }

        /* 搜索区域样式 - 修改为与product_list相似 */
        .search-area {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 8px;
            margin: 10px 0;
            width: 100%;
        }

        .search-row {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
        }

        .search-item {
            flex: 0 0 auto;
            margin-right: 10px;
            margin-bottom: 5px;
        }

        .search-item .form-control,
        .search-item .form-select {
            width: 120px;
            height: 31px;
            font-size: 14px;
        }

        .search-item .btn {
            padding: 4px 8px;
        }

        .search-label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
            color: #555;
            white-space: nowrap;
        }

        /* 表格样式 */
        .table-responsive {
            overflow-x: auto;
            margin: 0 -20px;
            padding: 0 20px;
        }

        .custom-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
        }

        .custom-table th {
            background: #f8f9fa;
            color: #495057;
            font-weight: 600;
            padding: 12px 15px;
            border-bottom: 2px solid #dee2e6;
            white-space: nowrap;
        }

        .custom-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
            vertical-align: middle;
        }

        /* 操作按钮样式 */
        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .action-buttons .btn {
            padding: 4px 10px;
            font-size: 13px;
        }

        /* 页面标题样式 */
        .page-title {
            font-size: 22px;
            font-weight: 600;
            margin-bottom: 20px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .page-title-icon {
            font-size: 24px;
        }

        /* 添加自动外边距，使元素靠右 */
        .ms-auto {
            margin-left: auto;
        }

        /* 添加按钮样式 */
        .add-button {
            padding: 8px 16px;
            display: flex;
            align-items: center;
            gap: 5px;
            font-weight: 500;
        }

        /* 内容区域样式 */
        .content-wrapper {
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            margin: 20px;
        }
        /* iOS风格模态框样式 */
        .ios-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.4);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1050;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .ios-modal.show {
            display: flex;
            opacity: 1;
        }

        .ios-modal-content {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 0;
            max-width: 400px;
            width: 90%;
            max-height: 80vh;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
            transform: scale(0.8);
            transition: transform 0.3s ease;
        }

        .ios-modal.show .ios-modal-content {
            transform: scale(1);
        }

        .ios-modal-header {
            padding: 20px 20px 10px;
            text-align: center;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }

        .ios-modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        .ios-modal-body {
            padding: 20px;
            max-height: 60vh;
            overflow-y: auto;
        }

        .ios-detail-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .ios-detail-item:last-child {
            border-bottom: none;
        }

        .ios-detail-label {
            font-weight: 500;
            color: #666;
            font-size: 14px;
        }

        .ios-detail-value {
            font-weight: 400;
            color: #333;
            font-size: 14px;
            text-align: right;
            max-width: 60%;
            word-wrap: break-word;
        }

        .ios-modal-footer {
            padding: 15px 20px 20px;
            text-align: center;
        }

        .ios-close-btn {
            background: #007AFF;
            color: white;
            border: none;
            border-radius: 12px;
            padding: 12px 30px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .ios-close-btn:hover {
            background: #0056CC;
        }

        /* 滚动条样式 */
        .ios-modal-body::-webkit-scrollbar {
            width: 4px;
        }

        .ios-modal-body::-webkit-scrollbar-track {
            background: transparent;
        }

        .ios-modal-body::-webkit-scrollbar-thumb {
            background: rgba(0, 0, 0, 0.2);
            border-radius: 2px;
        }
        /* 审批列表样式 */
        .approval-container {
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .form-row {
            display: flex;
            margin-bottom: 15px;
            flex-wrap: wrap;
            gap: 20px;
        }

        .form-group {
            flex: 1;
            min-width: 200px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-control {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .btn-container {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }

        .btn-secondary {
            background-color: #f0f0f0;
            color: #333;
        }

        .btn-success {
            background-color: #52c41a;
            color: white;
        }

        .btn-danger {
            background-color: #f5222d;
            color: white;
        }

        .btn:hover {
            opacity: 0.9;
        }

        /* 表格样式 */
        .approval-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .approval-table th, .approval-table td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }

        .approval-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }

        .approval-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        .status-pending {
            color: #faad14;
            font-weight: bold;
        }

        .status-approved {
            color: #52c41a;
            font-weight: bold;
        }

        .status-rejected {
            color: #f5222d;
            font-weight: bold;
        }

        /* 员工信息卡片 */
        .approver-info {
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
        }

        .approver-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background-color: #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            font-weight: bold;
            color: var(--primary-color);
            margin-right: 20px;
        }

        .approver-details {
            flex: 1;
        }

        .approver-name {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .approver-info-item {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
        }

        .approver-info-label {
            font-weight: bold;
            margin-right: 10px;
            min-width: 80px;
        }

        .result-message {
            margin-top: 20px;
            padding: 15px;
            border-radius: 4px;
            display: none;
        }

        .success-message {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #999;
        }

        /* 页面切换按钮样式 */
        .page-switch-container {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        .page-switch-btn {
            padding: 8px 16px;
            border: 1px solid #ddd;
            background: #f8f9fa;
            color: #333;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .page-switch-btn.active {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }

        .page-switch-btn:hover {
            background: #e9ecef;
        }

        .page-switch-btn.active:hover {
            background: var(--primary-color);
            opacity: 0.9;
        }

        /* 页面内容样式 */
        .page-content {
            display: none;
        }

        .page-content.active {
            display: block;
        }
    </style>
    <script>
        // 检查用户是否已登录，以及是否有权限访问该页面
        document.addEventListener('DOMContentLoaded', function () {
            // 检查用户是否已登录
            const userInfo = localStorage.getItem('userInfo');
            if (!userInfo) {
                // 未登录，跳转到登录页面
                window.location.href = '../../login.html';
                return;
            }

            try {
                const user = JSON.parse(userInfo);
                // 检查用户角色是否为部门经理
                if (user.role !== '部门经理') {
                    alert('您没有权限访问此页面');
                    window.location.href = '../../login.html';
                    return;
                }
            } catch (e) {
                // 解析错误，清除无效的用户信息
                localStorage.removeItem('userInfo');
                window.location.href = '../../login.html';
                return;
            }

            // 加载人员数据
            loadPersons();
        });
    </script>
</head>

<body>
<div class="admin-layout">
    <!-- 顶部导航栏 -->
    <header class="admin-header">
        <div class="header-left">
            <div class="logo">生产过程管理系统</div>
        </div>
        <div class="header-right">
            <span class="user-info">部门经理</span>
            <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
            <button class="logout-btn" onclick="logout()">退出</button>
        </div>
    </header>

    <!-- 左侧菜单 -->
    <aside class="admin-sidebar">
        <ul class="menu-list">
            <li class="menu-item">
                <a href="../homepage/manager_home.html">
                    <span class="menu-icon">🏠</span>
                    <span class="menu-title">首页</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">👥</span>
                    <span class="menu-title">人员管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../person/person_list.html" class="active">人员列表</a></li>
                    <li><a href="../person/person_edit.html">添加人员</a></li>
                    <li><a href="../person/schedule_edit.html">编辑排班表</a></li>
                    <li><a href="../person/schedule.html">查看排班表</a></li>
                    <li><a href="../person/schedule_statistics.html">班次统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📦</span>
                    <span class="menu-title">物料管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../material/material_list.html">物料列表</a></li>
                    <li><a href="*">物料采购统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">⚙️</span>
                    <span class="menu-title">设备管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../device/device_list.html">设备列表</a></li>
                    <li><a href="*">设备报修报废统计</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📝</span>
                    <span class="menu-title">产品管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../product/product_list.html">产品列表</a></li>
                    <li><a href="*">编辑生产计划</a></li>
                    <li><a href="*">查看生产计划</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">🏢</span>
                    <span class="menu-title">供应商管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../provider/provider_list.html">供应商列表</a></li>
                </ul>
            </li>
        </ul>
    </aside>

    <!-- 主内容区域 -->
    <main class="admin-main">
        <div class="content-wrapper">
            <!-- 页面切换按钮 -->
            <div class="page-switch-container">
                <button class="page-switch-btn active" onclick="switchPage('person')">人员管理</button>
                <button class="page-switch-btn" onclick="switchPage('leave')">请假审批</button>
            </div>

            <!-- 人员管理页面 -->
            <div id="person-page" class="page-content active">
                <!-- 页面标题 -->
                <div class="page-title">
                    <span class="page-title-icon">👥</span>
                    <span>人员列表</span>
                    <div class="ms-auto">
                        <button class="btn btn-success add-button" onclick="addPerson()">
                            <i class="fas fa-plus"></i> 添加人员
                        </button>
                    </div>
                </div>

                <!-- 搜索区域 -->
                <div class="search-area">
                    <div class="search-row">
                        <div class="search-item">
                            <label class="search-label">工号</label>
                            <input type="text" class="form-control form-control-sm" id="searchJobNumber"
                                   placeholder="请输入工号">
                        </div>
                        <div class="search-item">
                            <label class="search-label">姓名</label>
                            <input type="text" class="form-control form-control-sm" id="searchName"
                                   placeholder="请输入姓名">
                        </div>
                        <div class="search-item">
                            <label class="search-label">部门</label>
                            <select class="form-select form-select-sm" id="searchDepartment">
                                <option value="">全部</option>
                                <option value="表面处理车间">表面处理车间</option>
                                <option value="锻压车间">锻压车间</option>
                                <option value="组装车间">组装车间</option>
                                <option value="质检车间">质检车间</option>
                                <option value="机加车间">机加车间</option>
                            </select>
                        </div>
                        <div class="search-item">
                            <label class="search-label">最高学历</label>
                            <input type="text" class="form-control form-control-sm" id="searchEducation"
                                   placeholder="请输入学历">
                        </div>
                        <div class="search-item">
                            <label class="search-label">专业</label>
                            <input type="text" class="form-control form-control-sm" id="searchMajor"
                                   placeholder="请输入专业">
                        </div>
                        <div class="search-item">
                            <label class="search-label">职称</label>
                            <input type="text" class="form-control form-control-sm" id="searchTitle"
                                   placeholder="请输入职称">
                        </div>
                        <div class="search-item">
                            <label class="search-label">手机号</label>
                            <input type="text" class="form-control form-control-sm" id="searchPhone"
                                   placeholder="请输入手机号">
                        </div>
                        <div class="search-item">
                            <button class="btn btn-sm btn-outline-primary" onclick="searchPersons()">🔍</button>
                        </div>
                        <div class="search-item">
                            <button class="btn btn-sm btn-outline-secondary" onclick="resetSearch()">↺</button>
                        </div>
                    </div>
                </div>

                <!-- 数据表格 -->
                <div class="table-responsive">
                    <table class="table table-hover table-striped custom-table mb-0">
                        <thead>
                        <tr>
                            <th>工号</th>
                            <th>姓名</th>
                            <th>部门</th>
                            <th>入职时间</th>
                            <th>最高学历</th>
                            <th>专业</th>
                            <th>职称</th>
                            <th>手机号</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody id="personTableBody">
                        <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 请假审批页面 -->
            <div id="leave-page" class="page-content">
                <h1>请假审批</h1>

                <!-- 审批人信息卡片 -->
                <div class="approver-info">
                    <div id="approver-avatar" class="approver-avatar">?</div>
                    <div class="approver-details">
                        <div id="approver-name" class="approver-name">加载中...</div>
                        <div class="approver-info-item">
                            <span class="approver-info-label">工号:</span>
                            <span id="approver-job-number">加载中...</span>
                        </div>
                        <div class="approver-info-item">
                            <span class="approver-info-label">部门:</span>
                            <span id="approver-department">加载中...</span>
                        </div>
                    </div>
                </div>

                <!-- 审批列表容器 -->
                <div class="approval-container">
                    <!-- 结果消息 -->
                    <div id="result-message" class="result-message"></div>

                    <table class="approval-table">
                        <thead>
                        <tr>
                            <th>排班ID</th>
                            <th>请假原因</th>
                            <th>替班人员工号</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody id="approval-table-body">
                        <!-- 待审批记录将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>
</div>
<!-- iOS风格人员详情模态框 -->
<div class="ios-modal" id="personDetailModal">
    <div class="ios-modal-content">
        <div class="ios-modal-header">
            <h5 class="ios-modal-title">人员详情</h5>
        </div>
        <div class="ios-modal-body">
            <div class="ios-detail-item">
                <span class="ios-detail-label">姓名</span>
                <span class="ios-detail-value" id="detailName">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">工号</span>
                <span class="ios-detail-value" id="detailJobNumber">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">部门</span>
                <span class="ios-detail-value" id="detailDepartment">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">入职时间</span>
                <span class="ios-detail-value" id="detailEntryDate">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">最高学历</span>
                <span class="ios-detail-value" id="detailEducation">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">专业</span>
                <span class="ios-detail-value" id="detailMajor">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">职称</span>
                <span class="ios-detail-value" id="detailTitle">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">手机号</span>
                <span class="ios-detail-value" id="detailPhone">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">家庭住址</span>
                <span class="ios-detail-value" id="detailAddress">-</span>
            </div>
            <div class="ios-detail-item">
                <span class="ios-detail-label">个人简介</span>
                <span class="ios-detail-value" id="detailProfile">-</span>
            </div>
        </div>
        <div class="ios-modal-footer">
            <button class="ios-close-btn" onclick="closePersonDetailModal()">关闭</button>
        </div>
    </div>
</div>
<script src="../../assets/js/bootstrap.bundle.min.js"></script>
<script>
    // 菜单展开/收起功能
    document.addEventListener('DOMContentLoaded', function () {
        var menuItems = document.querySelectorAll('.menu-item > a');
        menuItems.forEach(function (item) {
            item.addEventListener('click', function (e) {
                var parent = item.parentElement;
                // 只允许单开一个折叠区
                document.querySelectorAll('.menu-item').forEach(function (el) {
                    if (el !== parent) el.classList.remove('active');
                });
                parent.classList.toggle('active');
                e.preventDefault();
            });
        });

        // 添加首页链接的点击事件
        document.querySelector('.menu-item:first-child > a').addEventListener('click', function (e) {
            e.preventDefault(); // 阻止默认行为
            window.location.href = '../homepage/manager_home.html'; // 跳转到管理员首页
        });

        // 默认展开人员管理菜单
        const personMenuItem = document.querySelector('.menu-item:nth-child(2)');
        if (personMenuItem) {
            personMenuItem.classList.add('active');
        }

        // 设置当前页面对应的菜单项为选中状态
        const currentPath = window.location.pathname;
        const filename = currentPath.substring(currentPath.lastIndexOf('/') + 1);
        document.querySelectorAll('.submenu li a').forEach(link => {
            if (link.getAttribute('href') === filename) {
                link.classList.add('active');
            }
        });

        // 加载人员数据
        loadPersons();
    });

    async function loadPersons() {
        try {
            const response = await fetch('http://localhost:8080/api/persons');
            const data = await response.json();
            displayPersons(data);
        } catch (error) {
            console.error('加载人员数据失败:', error);
        }
    }

    // 搜索人员
    function searchPersons() {
        const searchParams = {
            jobNumber: document.getElementById('searchJobNumber').value.toLowerCase(),
            name: document.getElementById('searchName').value.toLowerCase(),
            department: document.getElementById('searchDepartment').value,
            education: document.getElementById('searchEducation').value.toLowerCase(),
            major: document.getElementById('searchMajor').value.toLowerCase(),
            title: document.getElementById('searchTitle').value.toLowerCase(),
            phone: document.getElementById('searchPhone').value.toLowerCase()
        };

        const tbody = document.getElementById('personTableBody');
        const rows = tbody.getElementsByTagName('tr');

        for (let row of rows) {
            const cells = row.getElementsByTagName('td');
            const rowData = {
                jobNumber: cells[0].textContent.toLowerCase(),
                name: cells[1].textContent.toLowerCase(),
                department: cells[2].textContent,
                education: cells[4].textContent.toLowerCase(),
                major: cells[5].textContent.toLowerCase(),
                title: cells[6].textContent.toLowerCase(),
                phone: cells[7].textContent.toLowerCase()
            };

            let visible = true;
            for (const [key, value] of Object.entries(searchParams)) {
                if (value && !rowData[key].includes(value)) {
                    visible = false;
                    break;
                }
            }

            row.style.display = visible ? '' : 'none';
        }
    }

    // 重置搜索
    function resetSearch() {
        document.getElementById('searchJobNumber').value = '';
        document.getElementById('searchName').value = '';
        document.getElementById('searchDepartment').value = '';
        document.getElementById('searchEducation').value = '';
        document.getElementById('searchMajor').value = '';
        document.getElementById('searchTitle').value = '';
        document.getElementById('searchPhone').value = '';

        const tbody = document.getElementById('personTableBody');
        const rows = tbody.getElementsByTagName('tr');
        for (let row of rows) {
            row.style.display = '';
        }
    }

    // 显示人员数据
    function displayPersons(persons) {
        const tbody = document.getElementById('personTableBody');
        tbody.innerHTML = '';

        persons.forEach(person => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${person.jobNumber}</td>
                <td>${person.name}</td>
                <td>${person.department}</td>
                <td>${person.entryDate || ''}</td>
                <td>${person.education || ''}</td>
                <td>${person.major || ''}</td>
                <td>${person.title || ''}</td>
                <td>${person.phone || ''}</td>
                <td>
                    <div class="action-buttons">
                        <button class="btn btn-sm btn-info" onclick="editPerson(${person.id})">编辑</button>
                        <button class="btn btn-sm btn-danger" onclick="deletePerson(${person.id})">删除</button>
                        <button class="btn btn-sm btn-secondary" onclick="viewPersonDetail(${person.id})">详情</button>
                    </div>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    // 添加人员
    function addPerson() {
        window.location.href = 'person_edit.html';
    }

    // 编辑人员
    function editPerson(id) {
        window.location.href = `person_edit.html?id=${id}`;
    }

    // 查看人员详情 - iOS风格模态框
    function viewPersonDetail(id) {
        getPersonById(id).then(person => {
            if (person) {
                // 填充模态框数据
                document.getElementById('detailName').textContent = person.name || '未设置';
                document.getElementById('detailJobNumber').textContent = person.jobNumber || '未设置';
                document.getElementById('detailDepartment').textContent = person.department || '未设置';
                document.getElementById('detailEntryDate').textContent = person.entryDate || '未设置';
                document.getElementById('detailEducation').textContent = person.education || '未设置';
                document.getElementById('detailMajor').textContent = person.major || '未设置';
                document.getElementById('detailTitle').textContent = person.title || '未设置';
                document.getElementById('detailPhone').textContent = person.phone || '未设置';
                document.getElementById('detailAddress').textContent = person.address || '未设置';
                document.getElementById('detailProfile').textContent = person.profile || '未设置';

                // 显示模态框
                showPersonDetailModal();
            }
        });
    }

    // 显示iOS风格模态框
    function showPersonDetailModal() {
        const modal = document.getElementById('personDetailModal');
        modal.classList.add('show');

        // 点击背景关闭模态框
        modal.onclick = function (e) {
            if (e.target === modal) {
                closePersonDetailModal();
            }
        };
    }

    // 关闭iOS风格模态框
    function closePersonDetailModal() {
        const modal = document.getElementById('personDetailModal');
        modal.classList.remove('show');
    }

    // ESC键关闭模态框
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') {
            closePersonDetailModal();
        }
    });

    // 根据ID获取人员
    async function getPersonById(id) {
        try {
            const response = await fetch(`http://localhost:8080/api/persons/${id}`);
            const person = await response.json();
            return person;
        } catch (error) {
            console.error('获取人员详情失败:', error);
            return null;
        }
    }

    // 删除人员
    async function deletePerson(id) {
        if (confirm('确定要删除这个人员吗？')) {
            try {
                const response = await fetch(`http://localhost:8080/api/persons/${id}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    const result = await response.json();
                    alert(result.message); // 显示成功消息
                    loadPersons(); // 重新加载人员列表
                } else {
                    const error = await response.json();
                    alert(error.message || '删除失败');
                }
            } catch (error) {
                console.error('删除人员时出错:', error);
                alert('删除人员时发生错误，请稍后重试');
            }
        }
    }

    function logout() {
        // 添加确认提示
        if (confirm('确定要退出登录吗？')) {
            // 清除本地存储的登录信息
            localStorage.removeItem('userInfo');
            localStorage.removeItem('token');

            // 跳转到登录页面
            window.location.href = '../../login.html';
        }
    }

    // 存储所有请假申请数据
    let leaveApplications = [];

    // 页面切换功能
    function switchPage(pageType) {
        // 移除所有按钮的active类
        document.querySelectorAll('.page-switch-btn').forEach(btn => {
            btn.classList.remove('active');
        });

        // 隐藏所有页面内容
        document.querySelectorAll('.page-content').forEach(content => {
            content.classList.remove('active');
        });

        // 激活对应的按钮和页面
        if (pageType === 'person') {
            document.querySelector('.page-switch-btn[onclick="switchPage(\'person\')"]').classList.add('active');
            document.getElementById('person-page').classList.add('active');
        } else if (pageType === 'leave') {
            document.querySelector('.page-switch-btn[onclick="switchPage(\'leave\')"]').classList.add('active');
            document.getElementById('leave-page').classList.add('active');
            // 加载审批人信息和待审批记录
            loadApproverInfo();
            loadPendingApplications();
        }
    }

    // 加载审批人信息
    async function loadApproverInfo() {
        try {
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            if (!userInfo) {
                throw new Error('未找到用户信息');
            }

            // 显示审批人信息
            displayApproverInfo(userInfo);
        } catch (error) {
            console.error('获取审批人信息出错:', error);
            showMessage('获取审批人信息失败，请重新登录', false);
        }
    }

    // 显示审批人信息
    function displayApproverInfo(approver) {
        document.getElementById('approver-name').textContent = approver.name || '未知';
        document.getElementById('approver-job-number').textContent = approver.jobNumber || '未知';
        document.getElementById('approver-department').textContent = approver.department || '未知';
        document.getElementById('approver-avatar').textContent = (approver.name && approver.name.charAt(0)) || '?';
    }

    // 从API加载待审批的请假记录
    function loadPendingApplications() {
        showLoading(true);

        fetch('http://localhost:8080/api/leaves')
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                return response.json();
            })
            .then(data => {
                if (Array.isArray(data)) {
                    leaveApplications = data.filter(leave => !leave.isApproved);
                    displayPendingApplications(leaveApplications);
                } else {
                    leaveApplications = [];
                    displayPendingApplications([]);
                    showMessage('获取审批数据失败或数据格式不正确', false);
                }
            })
            .catch(error => {
                leaveApplications = [];
                displayPendingApplications([]);
                showMessage(`获取审批数据失败: ${error.message}`, false);
                console.error('加载待审批申请失败:', error);
            })
            .finally(() => {
                showLoading(false);
            });
    }

    // 显示待审批的请假记录
    function displayPendingApplications(applications) {
        const tableBody = document.getElementById('approval-table-body');
        tableBody.innerHTML = '';

        if (applications.length === 0) {
            const noDataRow = document.createElement('tr');
            noDataRow.innerHTML = `<td colspan="5" style="text-align: center; color: #999;">暂无待审批的请假记录</td>`;
            tableBody.appendChild(noDataRow);
            return;
        }

        applications.forEach(item => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${item.scheduleId}</td>
                <td>${item.description}</td>
                <td>${item.substituteJobNumber}</td>
                <td class="status-pending">待审批</td>
                <td>
                    <button class="btn btn-success" onclick="handleApproval(${item.id}, true)">批准</button>
                    <button class="btn btn-danger" onclick="handleApproval(${item.id}, false)">拒绝</button>
                </td>
            `;
            tableBody.appendChild(row);
        });
    }

    // 处理审批操作
    function handleApproval(applicationId, isApproved) {
        const application = leaveApplications.find(app => app.id === applicationId);
        if (!application) {
            showMessage('未找到对应的请假申请', false);
            return;
        }

        // 显示加载状态
        const btnContainer = event.target.parentElement;
        const originalHtml = btnContainer.innerHTML;
        btnContainer.innerHTML = '<span class="loading">处理中...</span>';

        // 构造审批数据
        const approvalData = {
            applicationId: applicationId,
            isApproved: isApproved,
            approverId: JSON.parse(localStorage.getItem('userInfo')).id,
            approvalTime: new Date().toISOString(),
            comment: isApproved ? '同意请假' : '拒绝请假'
        };

        // 调用API进行审批
        fetch('http://localhost:8080/api/leaves/approve', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(approvalData)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('审批操作失败');
                }
                return response.json();
            })
            .then(result => {
                if (result.success) {
                    // 更新本地数据
                    const index = leaveApplications.indexOf(application);
                    if (index > -1) {
                        leaveApplications.splice(index, 1);
                    }
                    showMessage(result.message, true);
                    displayPendingApplications(leaveApplications);
                } else {
                    showMessage(result.message || '审批操作失败', false);
                }
            })
            .catch(error => {
                showMessage(`审批操作失败: ${error.message}`, false);
                console.error('审批失败:', error);
            })
            .finally(() => {
                btnContainer.innerHTML = originalHtml;
            });
    }

    // 显示/隐藏加载状态
    function showLoading(show) {
        const tableBody = document.getElementById('approval-table-body');
        if (show) {
            tableBody.innerHTML = '<tr><td colspan="5" class="loading">加载审批数据中...</td></tr>';
        }
    }

    // 显示消息
    function showMessage(message, isSuccess) {
        const messageElement = document.getElementById('result-message');
        messageElement.textContent = message;
        messageElement.style.display = 'block';

        if (isSuccess) {
            messageElement.className = 'result-message success-message';
        } else {
            messageElement.className = 'result-message error-message';
        }

        setTimeout(() => {
            messageElement.style.display = 'none';
        }, 5000);
    }
</script>
</body>
</html>